package com.foreknow.elmboot.service.impl;



import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper orderMapper;

    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Autowired
    private CartMapper cartMapper;


    @Override
    public int updateorderState(Integer orderId) {
        return orderMapper.updateorderState(orderId);
    }

    @Override
    @Transactional
    public int createOrders(Orders order) {

        Cart cart = new Cart();
        List<Cart> carts=new ArrayList<>();
        List<OrderDetailet> orderDetailetArrayList=new ArrayList<>();
        //1查询当前购物车中商家的所有食品

        cart.setUserId(order.getUserId());
        cart.setBusinessId(order.getBusinessId());

        try {
            carts = cartMapper.listCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //2创建一订单（要返回一个订单的编号）
        order.setOrderDate(CommonUtil.getCurrentDate());
        orderMapper.saveOrders(order);

        //获取到添加的orderId，返回订单的id
        Integer orderId = order.getOrderId();

        //3 批量添加订单的明细
        for (Cart car : carts) {
            OrderDetailet od = new OrderDetailet();
            od.setOrderId(orderId);
            od.setFoodId(car.getFoodId());
            od.setQuantity(car.getQuantity());
            //将明细添加到orderDetailetArrayList
            orderDetailetArrayList.add(od);

        }
        orderDetailetMapper.saveOrderDetailetBatch(orderDetailetArrayList);

        //4从购物车中删除相关食品信息
        for (Cart c : carts) {
            try {
                cartMapper.deleteCart(c);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return orderMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrderByUserId(String userId) {
        return orderMapper.listOrderByUserId(userId);
    }


}
